import { PreviewData } from "@/api";
import {
  CodeMirrorEditor,
  PreviewAdapter,
  PreviewTreeAtom,
} from "@/components";
import { useStore } from "@/util/hooks";

interface TemplateDefEditorProps {
  height?: string;
}

function mergeEditorData(data: PreviewData[], selectedRecord: PreviewData) {
  const newData: PreviewData[] = [];
  for (const item of data) {
    if (item.absoluteUrl === selectedRecord.absoluteUrl) {
      newData.push(selectedRecord);
    } else {
      newData.push(item);
    }
  }
  return newData;
}

export const PreviewEditor = (props: TemplateDefEditorProps) => {
  const treeStore = useStore(PreviewTreeAtom);
  const previewTreeStore = useStore(PreviewTreeAtom);

  const { selectedRecord, originDataList } = treeStore.value;

  return (
    <CodeMirrorEditor
      height={props.height}
      width="100%"
      value={selectedRecord?.data}
      onChange={(value) => {
        if (!selectedRecord) {
          return;
        }
        treeStore.updateStore({
          selectedRecord: {
            ...selectedRecord,
            data: value,
          },
        });
      }}
      onBlur={() => {
        if (!selectedRecord) {
          return;
        }
        const newData = mergeEditorData(originDataList, selectedRecord);
        const treeData = PreviewAdapter.toTreeData(newData);
        previewTreeStore.updateStore({
          data: [...treeData],
          originDataList: [...newData],
        });
      }}
    />
  );
};
